package cn.est.serviceImpl;

import cn.est.constants.Constants;
import cn.est.exceptions.RedisException;
import cn.est.exceptions.TokenProtectedException;
import cn.est.pojo.Users;
import cn.est.service.TokenService;
import cn.est.utils.RedisUtil;
import cn.est.vo.TokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @ClassName TokenServiceImpl
 * @Description TODO
 * @Author yaozhaobao
 * @Date 2021/4/6 11:30
 * @Version 1.0
 **/
@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
   RedisUtil redisUtil ;


    @Override
    public TokenVo genenrateToken(Users users) {
        Long gentime = System.currentTimeMillis();
        String  account= users.getAccount()!=null?users.getAccount():users.getOpenId();
        String tokenKey="token:pc-"+gentime+"-"+ UUID.randomUUID().toString().replace("-","").substring(26)+"-"+account;
        TokenVo tokenVo = new TokenVo();
        tokenVo.setCreateTime(gentime);
        tokenVo.setOvertime(gentime+Constants.Token.VALID_TIME);
        tokenVo.setToken(tokenKey);
        return  tokenVo;
    }

    @Override
    public TokenVo refreshToken(String oldtoken) throws RedisException, TokenProtectedException {
        //1.有效性校验,校验redis中有没有token
            if(!redisUtil.hasKey(oldtoken)){
                throw new RedisException("redis不存在此token,过期了");
            }
        //2.oldtoken是否没有达到校验的时间，替换时间是oldtoken过期时间的前5分钟
           String oldTokenTime= oldtoken.split("-")[1];
            if(System.currentTimeMillis()-Long.parseLong(oldTokenTime)<Constants.Token.VALID_TIME-Constants.Token.NO_PROTEST_TIME){
                throw new TokenProtectedException("token还在保护期间，不允许置换token");
            }

        //3.生成新的token
            Users user= (Users) redisUtil.get(oldtoken);
            TokenVo tokenVo =genenrateToken(user);

        //4.新旧token替换
            saveToken(tokenVo.getToken(),user);

        //5.旧的token续命2分钟
            redisUtil.set(oldtoken,user,2*60);

        return tokenVo;
    }

    @Override
    public void saveToken(String token, Users users) {
        redisUtil.set(token,users, Constants.Duration.HALF_AN_HOUR_INT);
    }


}
